$(function(){
	// Code for the menu buttons
	var tpl = '{{#items}}'+
		'<div class="org">                 '+
				'  <label class="org-label">     '+
				'    <input type="checkbox" id="{{contactId}}" data-email="{{contactEmail}}"><span>{{contactEmail}}</span>  <span style="color:#777777">( {{remarkName}} )</span>       '+
				'  </label>                      '+
			  '</div>'  +
		'{{/items}}',
		appendTpl =  '<div class="org">                 '+
						'  <label class="org-label">     '+
						'    <input type="checkbox" id="{{contactId}}" data-email="{{email}}" checked=true><span>{{email}}</span>'+
						'  </label>                      '+
						'  {{#valid}}                      '+
						'  <span style="color: #B83F3F;font-weight: bold;">未注册用户</span>              '+
						'  {{/valid}}                     '+
					  '</div>'  ;
	thumbnailTpl = 
			'{{#members}}															'+
			'<div class="thumbnails-items">                                        '+
	        '    <div class="thumbnail">                                           '+
	        '		 <div class="removeIcon" userId="{{userId}}" data-email="{{email}}" data-mobile="{{mobile}}"></div>	                               '+
		    '        <div class="tmdetail">                                        '+
		    '      		<div class="tm-label">EMAIL:</div> <div class="tm-content" title={{email}}>{{email}}</div>                 '+
		    '      	</div>                                                         '+
	        '    	<div class="tmdetail">                                         '+
	        '      		<div class="tm-label">姓名:</div> <div class="tm-content" title={{name}}>{{name}}</div>                     '+
	        '      	</div>                                                         '+
	        '      	<div class="tmdetail">                                         '+
	        '      		<div class="tm-label">电话:</div> <div class="tm-content" title={{phone}}>{{phone}}</div>                  '+
	        '      	</div>                                                         '+
	        '      	<div class="tmdetail">                                         '+
	        '	{{#isRegister}} 													'+
	        '      		{{#isAgree}}                                               '+
	        '      			<div class="tm-label">状态:</div> <div class="tm-status">已同意  </div>                                 							'+
	        '      		{{/isAgree}}                                               '+
	        '      		{{^isAgree}}                                               '+
	        '      			<div class="tm-label">状态:</div> <div class="tm-statu">未同意</div> <div class="send_code" data-email="{{email}}"><a>重新发送</a></div>          '+
	        '      		{{/isAgree}}                                               '+
	        '	{{/isRegister}}														 '+
            '  			{{^isRegister}}                                            '+
            '  				<div class="tm-label">状态:</div> <div class="tm-statu">未注册</div><div class="invite_re" data-email="{{email}}"><a>邀请</a></div>             '+
            '  			{{/isRegister}}                                            '+
	        '      	</div>                                                         '+
	        '    </div>                                                            '+
	        '  </div>                                                              '+
		    ' {{/members}} ';
	$("#addUser_dlg").delegate("#orgUser-input","keyup" , function(e){
		if(e.which == 13)
		{
			var obj = {
					email : $("#orgUser-input").val()
			};
			if(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test($("#orgUser-input").val()) ){
				$.ajax({
					url : "/account/check.json",
					type : "post",
					data : {loginName: $("#orgUser-input").val()},
					async : false,
					success : function(data){
						if(!data.result)
						{
							obj["contactId"] = data.id;
						}
						else
						{
							obj["contactId"] = "";
							obj["valid"] = true;
						}
					}
				});
				if( _.contains( $("#addUser_dlg").data("restEmail") ,  obj.email) )
				{
					_.each($("#orgUser .org input") , function(data , index){
						if( $(data).attr("data-email") ==  obj.email )
						{
							$(data).prop("checked" , true);
							return false;
						}
					});
				}
				else
				{
					$("#orgUser").append(Mustache.to_html(appendTpl, obj));
				}
				
				$("#addUser_dlg .error-msg").empty();
				$("#orgUser-input").focus().val("");
			}
			else
			{
				$("#addUser_dlg .error-msg").html("邮件账号不合法");
			}
		}
		else
		{
			$(".error-msg").empty();
		}
	});
	
	
	var bind_thumbnail = function( instId ){
		$(".removeIcon").bind('click' , function(e){
			var that = $(this);
			$.ajax({
				type : "delete",
				url : "/account/institution/"+instId+"/member/"+ ($(this).attr("data-email") ? $(this).attr("data-email") : $(this).attr("data-mobile")),
				dataType : "json",
				success : function(){
					that.parents(".thumbnails-items").remove();
					if($("#organization-right .thumbnails").children().length == 0)
					{
						$("#remove").show();
					}
				}
			});
		});
		
		$(".send_code,.invite_re").bind('click' , function(e){
			var target = e.target , self = this;
			
			$.ajax({
				type : "put",
				url : "/account/institution/"+instId+"/invite/"+ $(this).attr("data-email"),
				dataType : "json",
				success : function(){
					$(target).html("已发送");
					$(self).unbind('click');
				}
			});
		});
	};
	
	$("#select_all").prop("checked" , false);
	$("#orgUser").delegate("[type='checkbox']" , 'click'  , function(e){
		if(!$(this).prop("checked")){
			$("#select_all").prop("checked" , false);
		}
		$("#addUser_dlg .error-msg").empty();
	});
	$("#addUser_dlg , #delete_dlg").on("show" , function( ){
		$(this).css({
        	left: ($(window).width() - $(this).width())/2,
        	top: 100
    	});
	}).draggable({
        containment: 'body',
        handle: '.modal-header'
    });
	
	$("#delete_dlg").delegate( "#fdelete" , "click" , function(e){
		$("#organization-left").jstree("remove" ,$(".jstree-clicked").parent());
	});
	
	
	$("#addUser_dlg").delegate( "#add_ok" ,'click' , function(e){
		var instId = $(".jstree-clicked").parent().attr("id");
		var userIds = [];
		_.each($("#orgUser .org input") , function(data , index){
			if( $(data).prop("checked") )
			{
				userIds.push( $(data).attr("data-email") );
			}
		})
		if( userIds.length>0 )
		{
			$.ajax({
				url :"/account/institution/"+instId+"/member",
				type : "post",
				dataType : "json",
				traditional: true,
				data :{
					institutionId : instId,
					userIds :userIds
				},
				success :function(data){
					$("#addUser_dlg").modal('hide');
					_.each(data.org.members , function(member){
						member["isAgree"] = false;
						member["isReject"] = false;
						member["isRegister"] = true;
						switch ( parseInt(member.status) ) {
						case 1:
							member["isAgree"] = false;
							break;
						case 2:
							member["isAgree"] = true;					
							break;
						case 3:
							member["isReject"] = true;
							break;
						case 4:
							member["isRegister"] = false;
							break;
						default:
							break;
						}
					});
					$("#organization-right .thumbnails").html( Mustache.to_html(thumbnailTpl, data.org) );
					bind_thumbnail(instId);
				}
			});
		}
		else
		{
			$("#addUser_dlg .error-msg").html("您未选择任何人员");
		}
	});
	$("#select_all").click(function(e){
		if( $(this).prop("checked") )
		{
			$("#orgUser .org input").prop("checked" , true);
		}
		else
		{
			$("#orgUser .org input").prop("checked" , false);
		}
	});
	$("#organization-head .nav li").click(function () {
		switch(this.id) {
			case "add_institution":
				$("#organization-left").jstree("create", null, "last",{"attr" : {
					"rel" : "institution"
				}});
				break;
			case "add_user":
				var instId = $(".jstree-clicked").parent().attr("id"),instData=[]; 
				userIds = [];
				$.ajax({
					url : "/account/institution/"+ instId +"/member",
					async : false,
					dataType : "json",
					success : function(data){
						instData = data.members;
					}
				});
				$.ajax({
					url : "/account/communicateBook/list.json",
					success : function(dataItems){
						$("#select_all").prop("checked" , false);
						$("#addUser_dlg").modal({
					        keyboard: true,
				    		show:true
					    });
						
						var restItems = dataItems.items , arr=[];
						
						_.each( instData , function( inst ){
							_.each( dataItems.items , function ( data , index){
								if( data.contactId == inst.userId)
								{
									restItems.splice(index ,1); 
									return false;
								}
								
							});
						});
						
						_.each(dataItems.items , function(data , index){
							var sname =  data.contactEmail ;
							arr.push(sname);
						})
						$("#addUser_dlg").data("restEmail" , arr);
						/*$("#orgUser-input").autocomplete({
							source : arr
						})*/
						$("#orgUser").html(Mustache.to_html(tpl, dataItems));
					}
				});
				break;
			case "add_organization":
				$("#organization-left").jstree("create", -1, "last",{"data" :""});
				break;
			case "remove" : 
				if( $(".jstree-clicked").next().is("ul") || $("#organization-right .thumbnails .thumbnails-items").length > 0)
				{
					$("#delete_dlg").modal({
						keyboard: true,
			    		show:true
					});
					$("#delete_dlg").data("force" , true);
				}
				else
				{
					$("#organization-left").jstree(this.id);
				}
				break;
			default:
				$("#organization-left").jstree(this.id);
				break;
		}
	});
	
	$("#text").click(function(e){
			$("#organization-left").jstree("search", $("#textInput").val());
	});
	$("#clear_search").click(function(e){
			$("#organization-left").jstree(this.id);
			$("#textInput").val("");
	});
	
	$("#menu .nav li").hover(function(){
		$(this).addClass("active");
	} , function(){
		$(this).removeClass("active");
	});
	
	var jsonData= jsonData||{} ,
	ownerId = "",
	getSeq = function(obj){
		var children = obj.parent().children(),
		length = children.length,
		seq = "";
		for(var i=0 ; i < length ; i++)
		{
			if( $(children[i]).attr("id") == obj.attr("id") )
			{
				seq = i+1; 
				break;
			}
		}
		return parseInt(seq);
	};
	
	$("#organization_tab").click(function(){
	$.ajax({
		url : "/account/org.json",
		success : function(data){
			jsonData = data.data,
			ownerId = jsonData.owner,
			initNode = jsonData[0] ? jsonData[0].metadata.id : "";
			if( !$("#organization-left > ul").children().is("li") )
			{
				$("#menu .nav li").hide();
				$("#add_organization").show();
			}
			$("#organization-left").jstree({ 
				"json_data" : {
					data : jsonData
				},
				"themes" : {
		            "theme" : "apple",
		            "url"   : "js/libs/jquery/jstree/themes/apple/style.css",
		            "dots" : false,
		            "icons" : true
		        },
		        "plugins" : [
			            "themes","json_data","ui","crrm","cookies","dnd","search","types"
			        ],
		     
				"search" : {
					
				},
				/*"dnd" : {
					"drop_target" : "#orgUser",
					"drop_finish" : function(){
						alert(123);
					},
					
					"drag_check" : function (data) {
		                alert(123)
					},
						            
					"drag_finish" : function (data) {
		                alert("DRAG OK");
		            }

				},
				
				"crrm" : {
		            "move" : {
		                
		            }
		        },*/

					        
				"types" : {
					
					"valid_children" : [ "organization" ],
					"types" : {
						"user" : {
							"valid_children" : "none",
							"icon" : {
								"image" : "js/libs/jquery/jstree/themes/apple/user.png"
							}
						},
						"user_invalid" : {
							"valid_children" : "none",
							"icon" : {
								"image" : "js/libs/jquery/jstree/themes/apple/user.png"
							}
						},
						"organization" : {
							"valid_children" : [ "institution" ],
							"icon" : {
								"image" : "js/libs/jquery/jstree/themes/apple/organization.png"
							}
						},
						"institution" :{
							"valid_children" : [ "user" , "institution" ,"user_invalid"],
							"icon" : {
								"image" : "js/libs/jquery/jstree/themes/apple/institution.png"
							}
						}
					}
				},
				
				"ui" : {
					"select_limit" : 1,
					"initially_select" : [initNode]
				},
				
				"core" : { 
					"strings"     : {
						"new_node" : "新建",
						"loading" : "loading"
					}
				}
			}).bind("create.jstree", function (e, data) {
					if( data.rslt.obj.attr("rel") == "organization" )
					{
						$.ajax({
							url :"/account/org",
							type : "post",
							dataType : "json",
							data :{
								name : data.rslt.name
							},
							success :function(res){
								data.rslt.obj.attr({
									"id" : res.org.id
								});
							}
							,error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
					else if( data.rslt.obj.attr("rel") == "institution" )
					{
						$.ajax({
							url :"/account/institution/"+data.rslt.parent.attr("id"),
							type : "post",
							dataType : "json",
							data :{
								name : data.rslt.name,
								parentId : data.rslt.parent.attr("id")
							},
							success :function(res){
								data.rslt.obj.attr({
									"id" : res.org.id
								});
							}
							,error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
					else if( data.rslt.obj.attr("rel") == "user" )
					{
						
					}
				})
				.bind("remove.jstree", function (e, data) {
					var ele = data.rslt.obj;
					if( data.rslt.obj.attr("rel") == "organization" )
					{
						$.ajax({
							type :"delete",
							url : "/account/org/" + data.rslt.obj.attr("id") + ( $("#delete_dlg").data("force") ? "?force" : "" ),
							dataType : "json",
							data : {
								orgId :data.rslt.obj.attr("id")
							},
							success : function(){
								$("#delete_dlg").modal("hide");
								if( !$("#organization-left > ul").children().is("li") )
								{
									$("#menu .nav li").hide();
									$("#add_organization").show();
								}
							},
							error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
					else if(data.rslt.obj.attr("rel") == "institution"){
						$.ajax({
							type :"delete",
							url : "/account/institution/" + data.rslt.obj.attr("id")+ ( $("#delete_dlg").data("force") ? "?force" : "" ),
							dataType : "json",
							data : {
								orgId :data.rslt.obj.attr("id")
							},
							success : function(){
								$("#delete_dlg").modal("hide");
							},
							error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
				})
				.bind("rename.jstree", function (e, data) {
					var seq = getSeq( data.rslt.obj );
					
					if( data.rslt.obj.attr("rel") == "organization" )
					{
						$.ajax({
							type :"put",
							url : "/account/org/" + data.rslt.obj.attr("id"),
							dataType: "json",
							data : {
								name :data.rslt.new_name,
								seq : seq,
								orgId : data.rslt.obj.attr("id")
							},
							success : function(){
								
							},
							error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
					else if(data.rslt.obj.attr("rel") == "institution"){
						$.ajax({
							type :"put",
							url : "/account/institution/" + data.rslt.obj.attr("id"),
							dataType: "json",
							data : {
								name :data.rslt.new_name,
								seq : seq,
								orgId : data.rslt.obj.attr("id")
							},
							success : function(){
								
							},
							error : function(){
								$.jstree.rollback(data.rlbk);
							}
						});
					}
				}).bind("select_node.jstree" , function(data , node){
					var rel = node.rslt.obj.attr("rel") ,instId = node.rslt.obj.attr("id") , ele = node.rslt.obj ;
					$("#menu .nav >li").show();
					switch (rel) {
					case "institution":
						$.ajax({
							url : "/account/institution/"+instId+"/member",
							dataType : "json",
							success : function(data){
								$("#organization-right .thumbnails").empty();
								_.each(data.members , function(member){
									member["isAgree"] = false;
									member["isReject"] = false;
									member["isRegister"] = true;
									switch ( parseInt(member.status) ) {
									case 1:
										member["isAgree"] = false;
										break;
									case 2:
										member["isAgree"] = true;					
										break;
									case 3:
										member["isReject"] = true;
										break;
									case 4:
										member["isRegister"] = false;
										break;
									default:
										break;
									}
								});
								$("#organization-right .thumbnails").html( Mustache.to_html(thumbnailTpl, data) );
								bind_thumbnail(instId);
							}
						});
						break;
					case "organization"	:
						$("#add_user").hide();
						$("#organization-right .thumbnails").empty();
						break;
					default:
						break;
					}
				}).bind("move_node.jstree" , function(event , data){
					var parentId = data.rslt.cr.attr("id"),objId = data.rslt.o.attr("id"),name = data.rslt.o.find(">a").text();
					var seq = getSeq(data.rslt.o);
					$.ajax({
						type : "put",
						url : "/account/org/" + objId,
						dataType : "json",
						data : {
							parentId : parentId,
							seq : seq,
							orgId : objId,
							name : name
						}
						,error : function(){
							$.jstree.rollback(data.rlbk);
						}
					});
				}).bind("loaded.jstree", function (event, data) {
		            $(this).jstree("open_all");
		        }).bind("hover_node.jstree", function (data , node) {
		            
		        })
				;
	        }
		});
	});
	if( window.location.hash == "#organization" )
	{
		$("#organization_tab").trigger("click");
	}
	
});
